package com.zz.server;

import com.zz.common.exception.TunnelException;
import com.zz.common.tunnel.Tunnel;
import com.zz.common.tunnel.TunnelHelper;
import com.zz.server.config.TunnelServerConfig;
import com.zz.server.factory.ServerBootstrapFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;

import java.net.BindException;
import java.util.Arrays;
import java.util.Collections;

@Slf4j
public class TunnelHttpApplication implements Tunnel {


    private final ServerBootstrap bootstrap;

    private final NioEventLoopGroup serverBossGroup;

    private final NioEventLoopGroup serverWorkGroup;

    public TunnelHttpApplication() {
        serverBossGroup = new NioEventLoopGroup();
        serverWorkGroup = new NioEventLoopGroup();
        bootstrap = ServerBootstrapFactory.createHttpBootstrap(serverBossGroup, serverWorkGroup);
    }

    @Override
    public void start() {
        TunnelServerConfig.getInstance().getHttpPortList().forEach(port -> {
            try {
                bootstrap.bind(TunnelServerConfig.getInstance().getServerBind(), port).get();
                log.info("proxy server start on port " + port);
            } catch (Exception ex) {
                // BindException表示该端口已经绑定过
                if (!(ex.getCause() instanceof BindException)) {
                    log.error("端口已被其他服务程序占用请重新尝试其他端口！");
                }
                throw new TunnelException("启动绑定端口异常！error message:{}", ex.getMessage());
            }
        });
    }

    @Override
    public void stop() {
        serverBossGroup.shutdownGracefully();
        serverWorkGroup.shutdownGracefully();
    }


}
